<template>
  <!-- 顶部显示用户信息的下拉框 -->
  <div class="dropdown"
       ref="dropdownRef">
    <a href="#"
       class="btn btn-outline-light my-2 dropdown-toggle"
       @click.prevent="toggleOpen">{{ title }}</a>
    <ul class="dropdown-menu"
        :style="{ display: 'block' }"
        v-if="isOpen">
      <slot></slot>
    </ul>
  </div>
</template>

<script lang='ts'>
import useClickOutside from '@/hook/useClickOutside'
import { defineComponent, ref, watch } from 'vue'
// export interface XXX { }
export default defineComponent({
  name: 'Dropdown',
  props: {
    title: {
      type: String,
      requied: true
    }
  },
  setup() {
    //点击展开下拉菜单
    const isOpen = ref(false)
    const toggleOpen = () => {
      isOpen.value = !isOpen.value
    }

    //点击外部区域自动隐藏
    const dropdownRef = ref<null | HTMLElement>(null)
    const isClickOutside = useClickOutside(dropdownRef)
    //只能执行一次,需要监视变化
    // if (isOpen.value && isClickOutside.value) {
    //   isOpen.value = false
    // }
    watch(isClickOutside, () => {
      if (isOpen.value && isClickOutside.value) {
        isOpen.value = false
      }
    })

    return {
      isOpen,
      toggleOpen,
      dropdownRef,

    }
  }
})
</script>

<style scoped>
</style>